﻿using System;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.IO;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Presentation;
using MathNet.Numerics;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using NPOI.XSSF.UserModel;
using Toxy;
using Match = System.Text.RegularExpressions.Match;

namespace Growatt.CreateCCode
{
    public class project_FirstVersion
    {
        public static void BuildingCode(string[] args)
        {
            try
            {
                Console.WriteLine("生成代码进行中...");
                RecordFile(Path.Combine(args[0], "..", "06_TbaleDocument", Program.config.FileModeCustom_Mode1), path2);
                Console.ReadLine();
                Environment.Exit(0);
            }
            catch (Exception EX)
            {
                Console.WriteLine("excel已打开/表格输入内容不规范/联系开发,生成代码失败!");
                Console.ReadLine();
            }
        }

        public static void BuildingCode0623(string[] args)
        {
            try
            {
                Console.WriteLine("生成代码进行中...");
                RecordFile0623(Path.Combine(args[0], "..", "06_TbaleDocument", Program.config.FileModeSafetyMode_2), path2);
                Console.ReadLine();
                Environment.Exit(0);
            }
            catch (Exception EX)
            {
                Console.WriteLine("excel已打开/表格输入内容不规范/联系开发,生成代码失败!");
                Console.ReadLine();
            }
        }

        public static List<string> GetcellValue(string path, string Sheetname, int rowindex, int colindex, int rowindex2, int colindex2)
        {
            List<string> list = new List<string>();
            // 打开Excel文件
            FileStream file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            ISheet sheet = workbook.GetSheet(Sheetname);
            IRow row = sheet.GetRow(rowindex);
            ICell cell = row.GetCell(colindex);

            IRow row2 = sheet.GetRow(rowindex2);
            ICell cell2 = row2.GetCell(colindex2);
            var cellval2 = cell2.StringCellValue;
            var cellval = cell.StringCellValue;

            list.Add(cellval.ToString());
            list.Add(cellval2.ToString());
            return list;
        }

        static int Rowcount = 0;
        static int Rowcount2 = 0;

        public static void changeCellValue(string path, Dictionary<string, List<(int, int, int, string, string)>> values)
        {
            try
            {
                // 打开Excel文件
                FileStream file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
                XSSFWorkbook workbook = new XSSFWorkbook(file);

                foreach (var item in values)
                {
                    var sheetName = item.Key;
                    ISheet sheet = workbook.GetSheet(sheetName);
                    for (global::System.Int32 i = 0; i < item.Value.Count; i++)
                    {
                        (int SetCellValue, int row, int column, string paraname, string lastsheetname) data = item.Value[i];

                        Action<int, int, string> action = (rowindex, column, SetCellValue) =>
                        {
                            /// 获取要修改的单元格
                            IRow row = sheet.GetRow(rowindex);
                            if (row == null)
                            {
                                row = sheet.CreateRow(rowindex);
                            }
                            ICell cell = row.GetCell(column);
                            if (cell == null)
                            {
                                cell = row.CreateCell(column);
                            }
                            cell.SetCellValue(SetCellValue); // 设置为新的数值

                            //// 创建新的样式
                            //XSSFCellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();
                            //style.FillForegroundColor = IndexedColors.Yellow.Index;
                            //style.FillPattern = FillPattern.SolidForeground;

                            //// 设置单元格的样式
                            //cell.CellStyle = style;
                        };
                        // 设置单元格的数值

                        action(data.row, data.column, data.SetCellValue.ToString());
                        if (!string.IsNullOrEmpty(data.lastsheetname))
                            action(data.row, data.column + 1, data.lastsheetname);
                        if (!string.IsNullOrEmpty(data.paraname))
                            action(data.row, data.column + 2, data.paraname);
                    }
                }
                // 修改指定cell的数值

                // 保存修改后的Excel文件
                file.Close();
                FileStream outFile = new FileStream(path, FileMode.Create);
                workbook.Write(outFile);
                outFile.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("excel已打开/表格输入内容不规范/联系开发,生成代码失败!");
                Console.ReadLine();
                Environment.Exit(0);
            }
        }

        public void orderdata(string path, string sheetName)
        {
            // 打开Excel文件
            FileStream file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            ISheet sheet = workbook.GetSheet(sheetName);

            // 获取要排序的列
            int columnIndex = 0; // 假设要排序的列是第一列

            // 获取要排序的数据范围
            int rowCount = sheet.LastRowNum + 1;
            CellType cellType = sheet.GetRow(0).GetCell(columnIndex).CellType;

            // 将数据读取到数组中
            object[,] data = new object[rowCount, 2];
            for (int i = 0; i < rowCount; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row != null)
                {
                    ICell cell = row.GetCell(columnIndex);
                    if (cell != null)
                    {
                        var re = cellType == CellType.Numeric;
                        if (re)
                            data[i, 0] = cell.NumericCellValue;
                        else
                            data[i, 0] = cell.StringCellValue;
                        data[i, 1] = i;
                    }
                }
            }

            // 对数据进行排序(在原数据上进行排序)
            Array.Sort(data);

            // 将排序后的数据写回表格
            for (int i = 0; i < rowCount; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row != null)
                {
                    ICell cell = row.GetCell(columnIndex);
                    if (cell != null)
                    {
                        int originalIndex = (int)data[i, 1];
                        object value = data[i, 0];
                        if (cellType == CellType.Numeric)
                        {
                            cell.SetCellValue(Convert.ToDouble(value));
                        }
                        else
                        {
                            cell.SetCellValue(value.ToString());
                        }
                    }
                }
            }

            // 保存修改后的Excel文件
            file.Close();
            FileStream outFile = new FileStream(path, FileMode.Create);
            workbook.Write(outFile);
            outFile.Close();
        }

        static string path1 = string.Empty;
        static string path2 = string.Empty;
        private static string pathCurrent = string.Empty;

        /// <summary>
        /// 生成txt
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void RecordFile(string pathFile, string txtpath)
        {
            try
            {
                Dictionary<string, List<string>> keyValuePairs = new Dictionary<string, List<string>>();
                Dictionary<(string, string), int> keyValuePairs_Sheet = new Dictionary<(string, string), int>();
                string Path = pathFile;
                if (!string.IsNullOrEmpty(Path))
                {
                    if (!string.IsNullOrEmpty(Path))
                    {
                        List<string> strings2 = new List<string>();
                        Rowcount = 0;
                        Rowcount2 = 0;
                        List<string> stringBuildersList = new List<string>();
                        List<string> NameList = new List<string>();
                        var lstdb = ReadFromExcelToDatatype(Path, null);
                        var datCount = lstdb.Where(o => o.TableName == "表结构体" || o.TableName == "总结构体").Count();
                        //if (datCount <= 0) //如果没有找sheet 直接退出
                        //    return;
                        var DatatableName = string.Empty;
                        if (lstdb != null && lstdb.Count > 0)
                        {
                            for (int k = 0; k < lstdb.Count; k++)
                            {
                                var datab = lstdb[k];
                                if (datab.TableName == "总结构体" || datab.TableName == "表结构体")
                                {
                                    continue;
                                }
                                //if (datab.TableName == "总结构体" || datab.TableName == "表结构体")
                                //{
                                //    if (datab.TableName == "表结构体")
                                //    {
                                //        List<string> strlistTranslate = new List<string>() { "MyProperty1", "MyProperty2", "MyProperty3", "MyProperty4", "MyProperty5", "MyProperty6", "MyProperty7", "MyProperty8", "MyProperty9" };
                                //        for (int i = 0; i < strlistTranslate.Count; i++)
                                //        {
                                //            datab.Columns[i].ColumnName = strlistTranslate[i];
                                //        }
                                //        var TranslateModel = HelperImport.DataTableToList<DataModelStructureConfig>(datab);
                                //        if (TranslateModel != null && TranslateModel.Count > 0) {

                                //            Debug.WriteLine("生成表结构体成功!"  );

                                //        }

                                //            for (int i = 0; i < datab.Rows.Count; i++)
                                //        {
                                //            var row = (DataRow)datab.Rows[i];
                                //            var data2 = row[2].ToString();
                                //            strings2.Add(data2);

                                //        }
                                //    }
                                //    continue;
                                //}
                                //else
                                {
                                    keyValuePairs.Clear();
                                    keyValuePairs_Sheet.Clear();
                                    keyValuePairs.Add(datab.TableName, new List<string>());
                                    DatatableName += datab.TableName + ",";
                                    StringBuilder stringBuilderSingleTable = new StringBuilder();
                                    StringBuilder stringBuilderTemp = new StringBuilder();
                                    List<string> listSub = null;
                                    var strHeard = string.Empty;
                                    if (datab != null)
                                    {
                                        Debug.WriteLine(datab.TableName);
                                        List<string> strings = new List<string>();
                                        var dt = datab as DataTable;
                                        DataRow dr = dt.NewRow();
                                        dt.Rows.Add(dr);
                                        if (dt.Rows.Count > 0)
                                        {
                                            for (int i = 0; i < dt.Rows.Count; i++)
                                            {
                                                var row = (DataRow)dt.Rows[i];
                                                var data1 = "";
                                                var data2 = "";
                                                if (i != dt.Rows.Count - 1)
                                                {
                                                    try
                                                    {
                                                        if (row[1] != null && row[2] != null && !string.IsNullOrEmpty(row[1].ToString()) && !string.IsNullOrEmpty(row[2].ToString()))
                                                        {
                                                            data1 = row[1].ToString();
                                                            data2 = row[2].ToString();
                                                            strings.Add(data2);
                                                            if (!string.IsNullOrEmpty(data2.Split('[').ElementAtOrDefault(0)))
                                                            {
                                                                var str = data2.Split('[').ElementAtOrDefault(0);

                                                                if (!keyValuePairs[datab.TableName].Contains(str))
                                                                {
                                                                    keyValuePairs[datab.TableName].Add(str);
                                                                }
                                                            }
                                                        }
                                                        else
                                                            continue;
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Console.WriteLine("已打开/表格输入内容不规范/联系开发,生成代码失败!");
                                                        Console.ReadLine();
                                                    }
                                                }

                                                var strHeadtemp = $"const {data1} {data2} = {{";
                                                if (strHeard != strHeadtemp || i == dt.Rows.Count - 1)
                                                {
                                                    stringBuilderTemp.Append(strHeard);

                                                    if (listSub != null && listSub.Count > 0)
                                                    {
                                                        //listSub.Select(o => stringBuilderTemp.AppendLine(o + ",")).ToList();
                                                        listSub.Select(o => stringBuilderTemp.AppendLine(o)).ToList();
                                                        stringBuilderTemp.AppendLine("};");
                                                        stringBuilderSingleTable.AppendLine(stringBuilderTemp.ToString());
                                                        listSub = new List<string>();
                                                        stringBuilderTemp = new StringBuilder();
                                                        if (i == dt.Rows.Count - 1)
                                                        {
                                                            stringBuildersList.Add(stringBuilderSingleTable.ToString());
                                                            NameList.Add(txtpath);
                                                            break;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        listSub = new List<string>();
                                                    }
                                                    strHeard = strHeadtemp;
                                                }
                                                //获取每一行的参数
                                                string subString = "{";
                                                var lastRemark = "";

                                                txtpath = row.ItemArray[0] as string;
                                                for (int icc = 1; icc < row.ItemArray.Count(); icc++)
                                                {
                                                    if (icc > 2 && icc <= row.ItemArray.Count())
                                                    {
                                                        var itemString = "";
                                                        if (icc == row.ItemArray.Count() - 1) //倒数二列
                                                        {
                                                            lastRemark = $",\t/*{row.ItemArray[icc]}*/";
                                                        }
                                                        else if (icc == row.ItemArray.Count()) //倒数一列
                                                        { }
                                                        else
                                                        {
                                                            itemString = $"{row.ItemArray[icc]}";
                                                            if (itemString != null)
                                                            {
                                                                subString += itemString.ToString() + "," + "\t";
                                                            }
                                                        }
                                                    }
                                                }
                                                subString = DelLastComma(subString);
                                                subString += "}";
                                                subString += lastRemark;
                                                listSub.Add(subString);
                                            }

                                            //foreach (var item in keyValuePairs)
                                            //{
                                            //    for (int i = 0; i < item.Value.Count; i++)
                                            //    {
                                            //        var dats = strings.Where(o => o.Split('[').ElementAtOrDefault(0) == item.Value[i]).Count();
                                            //        if (!keyValuePairs_Sheet.ContainsKey((item.Key, item.Value[i])))
                                            //        {
                                            //            keyValuePairs_Sheet.Add((item.Key, item.Value[i]), dats);
                                            //        }
                                            //        //获取所有数组的
                                            //    }

                                            //}
                                            //try
                                            //{
                                            //    var datastrings = GetcellValue(Path, "总结构体", 1, 4, 2, 4);
                                            //    for (int i = 0; i < datastrings.Count; i++)
                                            //    {
                                            //        if (Rowcount2 <= 1)
                                            //        {
                                            //            Dictionary<string, List<(int, int, int, string, string)>> dic2 = new Dictionary<string, List<(int, int, int, string, string)>>();
                                            //            var dats = strings2.Where(o => o.Split('[').ElementAtOrDefault(0).Contains(datastrings[i]) && !string.IsNullOrEmpty(o.Split('[').ElementAtOrDefault(0))).Count();
                                            //            if (dats != 0)
                                            //            {
                                            //                List<(int, int, int)> klist1 = new List<(int, int, int)>();
                                            //                Rowcount2 = Rowcount2 + 1;
                                            //                dic2.Add("总结构体", new List<(int, int, int, string, string)>() { (dats, Rowcount2, 3, "", datastrings[i]) });
                                            //                changeCellValue(Path, dic2);
                                            //            }
                                            //        }
                                            //    }

                                            //}
                                            //catch (Exception ex)
                                            //{

                                            //}
                                            //List<(int, int, int)> klist = new List<(int, int, int)>();
                                            //Dictionary<string, List<(int, int, int, string, string)>> dic = new Dictionary<string, List<(int, int, int, string, string)>>();
                                            //foreach (var item in keyValuePairs_Sheet)
                                            //{
                                            //    Rowcount = Rowcount + 1;
                                            //    dic.Add("表结构体", new List<(int, int, int, string, string)>() { (item.Value, Rowcount, 5, item.Key.Item1, item.Key.Item2) });
                                            //}
                                            //lidtDic.Add(dic);
                                        }
                                    }
                                }
                            }
                        }
                        WriteFileByFileName(NameList, stringBuildersList);
                        foreach (var item in lidtDic)
                            changeCellValue(Path, item);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("已打开/表格输入内容不规范/联系开发,生成代码失败!");
                Console.ReadLine();
            }
        }

        static List<string> getData(string input)
        {
            // 定义正则表达式模式
            string pattern = @"\((.*?)\)";

            // 使用 Regex 匹配输入字符串
            var matches = Regex.Matches(input, pattern);

            List<string> contentsInsideParentheses = new List<string>();

            foreach (Match match in matches)
            {
                if (match.Success)
                {
                    // 提取括号内的内容
                    contentsInsideParentheses.Add(match.Groups[1].Value);
                }
            }
            contentsInsideParentheses.Add(input);
            return contentsInsideParentheses;
        }

        static List<string> getData2(string input)
        {
            // 定义正则表达式模式，只匹配数值
            string pattern = @"\[(\d+)\]";

            // 使用 Regex 匹配输入字符串
            var matches = Regex.Matches(input, pattern);

            List<string> contentsInsideParentheses = new List<string>();

            foreach (Match match in matches)
            {
                if (match.Success)
                {
                    // 提取括号内的内容
                    contentsInsideParentheses.Add(match.Groups[1].Value);
                }
                else
                {
                    contentsInsideParentheses.Add(input);
                }
            }

            return contentsInsideParentheses;
        }

        static List<ExcelModel> Get(List<ExcelModel> excelModels)
        {
            List<ExcelModel> list = new List<ExcelModel>();

            foreach (var item in excelModels)
            {
                string pattern = @"add\((\d+),(\d+)\)";

                // 使用 Regex 匹配输入字符串
                var match = Regex.Match(item.StartIndex, pattern);

                if (match.Success)
                {
                    // 提取匹配的数字
                    string firstNumber = match.Groups[1].Value;
                    string secondNumber = match.Groups[2].Value;
                    var dataVarNum = getData2(item.VariableName).FirstOrDefault(); //获取括号内的数据;
                    var preName = item.VariableName.Replace($"[{dataVarNum}]", "");
                    int index = 1;
                    for (int i = 0; i < int.Parse(secondNumber); i++)
                    {
                        list.Add(
                            new ExcelModel()
                            {
                                StartIndex = (int.Parse(firstNumber) + index).ToString(),
                                FileName = item.FileName,
                                FunctionName = item.FunctionName,
                                VariableName = preName + "[" + (int.Parse(dataVarNum) + index).ToString() + "]",
                                SheetName = item.SheetName,
                            }
                        );
                        index++;
                    }

                    // 输出结果
                    Console.WriteLine($"First Number: {firstNumber}, Second Number: {secondNumber}");
                }
                else
                {
                    Console.WriteLine("No match found.");
                }
            }

            return list;
            // 定义正则表达式式
        }

        static int CountCount = 10;
        static string SheetName = "默认";

        /// <summary>
        /// 生成txt
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///
        static void RecordFile0623(string filePath, string txtpath)
        {
            try
            {
                ExcelReader reader = new ExcelReader();
                CountCount = reader.ReadExcelFileColCount(filePath, CountCount);
                for (global::System.Int32 iCol = 10; iCol <= CountCount; iCol++)
                {

                    List<ExcelModel> models = reader.ReadExcelFile(filePath, iCol);

                    var col = models.FirstOrDefault(o => int.TryParse(o.ColCount, out int dataCol));
                    SheetName = col.Name;
                    Console.WriteLine(SheetName+"数量:" + models.Count);

                    // 定义正则表达式模式
                    // 这个模式匹配两个由波浪号'~'连接的数字，数字可以是任意长度的正整数
                    string pattern = @"^\d+~\d+$";

                    // 创建Regex对象
                    Regex regex = new Regex(pattern);
                    var patModel = models.Where(o => regex.IsMatch(o.StartIndex)).ToList();
                    foreach (var item in patModel)
                    {
                        item.StartIndex = "0";
                        item.StartIndexint = 0;
                    }
                    models = models.Where(o => !string.IsNullOrEmpty(o.FunctionName) && (int.TryParse(o.StartIndex, out int start) || o.StartIndex.Contains("add("))).ToList();
                    var list = models.Where(o => o.StartIndex.Contains("add(")&& !string.IsNullOrEmpty(o.VariableName)).ToList();

                    var modelsCre = Get(list);
                    models.AddRange(modelsCre);
                    var dd = models.Where(o => (!string.IsNullOrEmpty(o.FunctionName) && (int.TryParse(o.StartIndex, out int start)))).ToList();
                    dd.ForEach(o => o.StartIndexint = int.Parse(o.StartIndex));
                    models = dd;
                    models.AddRange(patModel);
                    var groupedModels = models
                        .Where(o => o.FunctionName.Contains("Send") || (o.FunctionName.Contains("Rec")))
                        .Where(o => !string.IsNullOrEmpty(o.FileName))
                        //.GroupBy(o => new { o.SheetName, o.FunctionName })
                        .GroupBy(o => o.FunctionName)
                        .ToList();

                    var groupedModelsFileName = models
                        .Where(o => o.FunctionName.Contains("Send") || (o.FunctionName.Contains("Rec")))
                        .Where(o => !string.IsNullOrEmpty(o.FileName))
                        .GroupBy(o => o.FileName) // 根据FileName进行分组
                        .ToList()
                        .Select(o => o);

                    var groupedModelsPointerName = models
                        .Where(o => o.FunctionName.Contains("Send") || (o.FunctionName.Contains("Rec")))
                        .Where(o => !string.IsNullOrEmpty(o.FileName))
                        .Where(o => !string.IsNullOrEmpty(o.PointerName))
                        .GroupBy(o => o.PointerName) // 根据FileName进行分组
                        .ToList()
                        .Select(o => o);

                    Dictionary<string, StringBuilder> DicFiles_FuncName_C = new Dictionary<string, StringBuilder>();
                    Dictionary<string, StringBuilder> DicFiles_FileName_C = new Dictionary<string, StringBuilder>();
                    Dictionary<string, StringBuilder> DicFiles_H = new Dictionary<string, StringBuilder>();
                    string namepointerName = ""; //函数名称绝对不能为空
                                                 // 遍历分组后的结果
                    foreach (var group in groupedModels)
                    {
                        var group1 = group.OrderBy(o => o.StartIndexint);
                        foreach (var model in group1)
                        {
                            if (!DicFiles_FuncName_C.ContainsKey(model.FunctionName))
                            {
                                namepointerName = model.FunctionName;
                                DicFiles_FuncName_C.Add(model.FunctionName, new StringBuilder());
                                DicFiles_FuncName_C[model.FunctionName].Append($"void {model.FunctionName}(INT8U* pubData)\n");
                                DicFiles_FuncName_C[namepointerName].AppendLine($"{{");
                            }

                            //接收函数体赋值变量，
                            //    若识别到变量包含 HIBYTE，
                            //    将 变量值 =  uwChrToWord(&pubData[字节位置])
                            //    赋值给括号中的变量，
                            //    若识别到变量包含 HHWORD，
                            //    将 udChrToDBWord(&pubData[字节位置])赋值给括号中的变量，
                            //    若识别到变量包含 LOBYTE、HLWORD、LHWORD 及 LLWORD 则跳过，无需赋值
                            if (model.FunctionName.Contains("Rec") && !string.IsNullOrEmpty(model.VariableName))
                            {
                                if ((model.VariableName.Contains("LOBYTE") || model.VariableName.Contains("HLWORD") || model.VariableName.Contains("LHWORD") || model.VariableName.Contains("LLWORD")))
                                    continue;

                                var name = model.VariableName;
                                var data = getData(name).FirstOrDefault();
                                if (model.VariableName.Contains("HHWORD"))
                                {
                                    DicFiles_FuncName_C[model.FunctionName].Append($"{data}=udChrToDBWord(&pubData[{model.StartIndex}]);\n");
                                }
                                else if (model.VariableName.Contains("HIBYTE"))
                                {
                                    DicFiles_FuncName_C[model.FunctionName].Append($"{data}=uwChrToWord(&pubData[{model.StartIndex}]);\n");
                                }
                                else
                                {
                                    DicFiles_FuncName_C[model.FunctionName].Append($"{data}=pubData[{model.StartIndex}];\n");
                                }
                            }
                            else if (model.FunctionName.Contains("Send") && !string.IsNullOrEmpty(model.VariableName))
                            {
                                DicFiles_FuncName_C[model.FunctionName].Append($"pubData[{model.StartIndex}]={model.VariableName};\n");
                            }
                        }
                        DicFiles_FuncName_C[namepointerName].AppendLine($"}}");
                    }
                    List<ExcelModelTotal> excelModelTotals = new List<ExcelModelTotal>();
                    // 遍历分组后的结果(根据方PointerName进行分组)
                    foreach (var group in groupedModelsPointerName)
                    {
                        //var group1 = group.OrderBy(o => o.StartIndexint);
                        var group1 = group;
                        ExcelModelTotal excelModelTotal = new ExcelModelTotal();
                        excelModelTotal.FileName = group1.FirstOrDefault().FileName;
                        excelModelTotal.Sb = new StringBuilder();
                        excelModelTotal.PonterName = group.Key;
                        excelModelTotal.Sb.Append($"void (*{excelModelTotal.PonterName}[])(unsigned char *pubData)=\n");
                        excelModelTotal.Sb.AppendLine($"{{");
                        foreach (var model in group1.Select(o => o.FunctionName).Distinct())
                        {
                            excelModelTotal.Sb.Append($"{model},\n");
                        }
                        excelModelTotal.Sb.AppendLine($"}};");
                        excelModelTotals.Add(excelModelTotal);
                    }
                    HashSet<string> modelsFileName = new HashSet<string>();
                    // 遍历分组后的结果(根据方法名进行分组)
                    foreach (var group in groupedModelsFileName)
                    {
                        //var group1 = group.OrderBy(o => o.StartIndexint);
                        foreach (var model in group)
                        {
                            modelsFileName.Add(model.FunctionName); // 输出函数名称作为分组键
                        }
                        DicFiles_H[group.Key] = new StringBuilder();
                        foreach (var item in modelsFileName)
                        {
                            DicFiles_H[group.Key].AppendLine($"extern void {item} (INT8U* pubData);");
                            var func = DicFiles_FuncName_C.Keys.FirstOrDefault(o => o == item); //将所有函数体写入到同一个文件(.h)中
                            if (!string.IsNullOrEmpty(func))
                            {
                                if (!DicFiles_FileName_C.ContainsKey(group.Key))
                                    DicFiles_FileName_C.Add(group.Key, new StringBuilder());
                                DicFiles_FileName_C[group.Key].AppendLine(DicFiles_FuncName_C[func].ToString()); //将所有函数体写入到同一个文件(.c)中
                            }
                        }
                        modelsFileName.Clear();
                    }
                    foreach (var item in excelModelTotals.GroupBy(o => o.FileName)) // 存进不同的文件中
                    {
                        if (DicFiles_FileName_C.ContainsKey(item.Key))
                        {
                            DicFiles_FileName_C[item.Key].Append($"#pragma pack(4)\n");
                            DicFiles_FileName_C[item.Key].Append(string.Join("", item.Select(o => o.Sb.ToString())));//将函数的函数名放置一起;
                            DicFiles_FileName_C[item.Key].AppendLine($"#pragma pack()");
                        }
                    }
                    foreach (var item in excelModelTotals.GroupBy(o => o.FileName))
                    {
                        if (DicFiles_H.ContainsKey(item.Key))
                        {
                            foreach (var item2 in item)
                            {
                                var fi = string.Join(Environment.NewLine, item2.Sb.ToString().Split('\n')[0].Replace("=", ""));//获取每个string的首行
                                DicFiles_H[item.Key].Append($"extern {fi};\n");
                            }

                        }
                    }
                    var key = DicFiles_FileName_C.Select(o => o.Key.ToString() + "_" + SheetName + ".c").ToList();
                    var val = DicFiles_FileName_C.Select(o => o.Value.ToString()).ToList();

                    var stringskey_h = DicFiles_H.Select(o => o.Key.ToString() + "_" + SheetName + ".h").ToList();
                    key.AddRange(stringskey_h);
                    var valstringsVal_h = DicFiles_H.Select(o => o.Value.ToString()).ToList();
                    val.AddRange(valstringsVal_h);
                    WriteFileByFileNameVers(key, val);

                }


            }
            catch (Exception ex)
            {
                Console.WriteLine("已打开/表格输入内容不规范/联系开发,生成代码失败!");
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }

        static List<Dictionary<string, List<(int, int, int, string, string)>>> lidtDic = new List<Dictionary<string, List<(int, int, int, string, string)>>>();

        /// <summary>
        /// 根据文件名称记录数据
        /// </summary>
        /// <param name="txtpaths"></param>
        /// <param name="stringBuildersList"></param>
        private static void WriteFileByFileName(List<string> txtpaths, List<string> stringBuildersList)
        {
            try
            {
                if (txtpaths.Count == stringBuildersList.Count)
                {
                    for (int i = 0; i < stringBuildersList.Count; i++)
                    {
                        var name = txtpaths[i];
                        var st = stringBuildersList[i];
                        var val = "".TrimEnd();
                        var dataTable = new System.Data.DataTable();
                        dataTable.Columns.Add(new DataColumn());
                        string listStr = st;
                        DataRow dr1 = dataTable.NewRow();
                        dataTable.Rows.Add(dr1);
                        dr1[0] = listStr;
                        if (dataTable != null && !string.IsNullOrEmpty(name))
                        {
                            string p = "";
                            if (name.Contains(".c"))
                            {
                                p = Path.Combine(pathCurrent, "..", Program.config.CodeDirectoryInfo, "source", name);
                                RemoveExist(p);
                            }
                            else if (name.Contains(".h"))
                            {
                                p = Path.Combine(pathCurrent, "..", Program.config.CodeDirectoryInfo, "include", name);
                                RemoveExist(p);
                            }
                            var result = DataToStringTXT2(name, dataTable, val, new List<int>() { dataTable.Columns.Count - 1 }, "Custom" + "_");
                        }
                    }
                    Console.WriteLine("生成成功!");
                    Environment.Exit(0);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("生成失败!");
            }
        }
        /// <summary>
        /// 根据文件名称记录数据
        /// </summary>
        /// <param name="txtpaths"></param>
        /// <param name="stringBuildersList"></param>
        private static void WriteFileByFileNameVers(List<string> txtpaths, List<string> stringBuildersList)
        {
            try
            {
                if (txtpaths.Count == stringBuildersList.Count)
                {
                    for (int i = 0; i < stringBuildersList.Count; i++)
                    {
                        var name = txtpaths[i];
                        var st = stringBuildersList[i];
                        var val = "".TrimEnd();
                        var dataTable = new System.Data.DataTable();
                        dataTable.Columns.Add(new DataColumn());
                        string listStr = st;
                        DataRow dr1 = dataTable.NewRow();
                        dataTable.Rows.Add(dr1);
                        dr1[0] = listStr;
                        if (dataTable != null && !string.IsNullOrEmpty(name))
                        {
                            string p = "";
                            if (name.Contains(".c"))
                            {
                                p = Path.Combine(pathCurrent, "..", Program.config.CodeDirectoryInfo, "source", name);
                                RemoveExist(p);
                            }
                            else if (name.Contains(".h"))
                            {
                                p = Path.Combine(pathCurrent, "..", Program.config.CodeDirectoryInfo, "include", name);
                                RemoveExist(p);
                            }
                            var result = DataToStringTXT2(name, dataTable, val, new List<int>() { dataTable.Columns.Count - 1 }, "Custom" + "_");
                        }
                    }
                    Console.WriteLine("生成成功!");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("生成失败!");
            }
        }
        /// <summary>
        /// 不同字典内部数据
        /// </summary>
        static Dictionary<string, bool> PathDicContent = new Dictionary<string, bool>();

        static void RemoveExist(string path)
        {
            if (!File.Exists(path))
                using (StreamWriter streamWriter = new StreamWriter(path, false, Encoding.GetEncoding("GB2312"))) { } //直接创建
            if (!PathDicContent.ContainsKey(path))
            {
                PathDicContent.Add(path, true);
                var strings = LoadFilelistString(path).ToList();
                var ind1 = 0;
                var ind2 = 0;
                var fin = false;
                for (int i = 0; i < strings.Count; i++)
                {
                    var itemstring = strings[i];

                    if (!fin && itemstring.Equals("/************************Excel spanned data start**********************/"))
                    {
                        ind1 = i;
                        fin = true;
                    }
                    if (itemstring.Equals("/************************Excel spanned data end**********************/"))
                    {
                        ind2 = i;
                    }
                }

                if (ind1 != 0 && ind2 != 0 && ind2 > ind1)
                {
                    var count = ind2 - ind1;
                    if (count > 0)
                    {
                        strings.RemoveRange(ind1, count + 1); //删除多余的行
                    }
                }
                if (!strings.Contains(fixData))
                    strings.Add(fixData);
                if (!keyValuePairs.ContainsKey(path)) //第一次需要添加原先内容
                {
                    keyValuePairs.Add(path, strings);
                }
            }
        }

        public static bool DataToStringTXT2(string txtpath, DataTable table, string strHeader, List<int> lstVisibleColumn = null, string fileName = "", bool ShowHeader = false)
        {
            bool result = false;
            try
            {
                string delimiter = ",";
                string path = "";
                if (txtpath.Contains(".c"))
                {
                    path = Path.Combine(pathCurrent, "..", $"{Program.config.CodeDirectoryInfo}", "source", txtpath);
                }
                else if (txtpath.Contains(".h"))
                {
                    path = Path.Combine(pathCurrent, "..", $"{Program.config.CodeDirectoryInfo}", "include", txtpath);
                }
                var strings = new List<string>();
                if (File.Exists(path))
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("GB2312"));
                    try
                    {
                        if (ShowHeader)
                            stringBuilder.AppendLine(strHeader);
                        stringBuilder.AppendLine();
                        stringBuilder.AppendLine("/************************Excel spanned data start**********************/");
                        stringBuilder.AppendLine("/*生成代码*/");
                        for (int i = 0; i < table.Rows.Count; i++)
                        {
                            string strBufferLine = "";
                            for (int j = 0; j < table.Columns.Count; j++)
                            {
                                if (lstVisibleColumn != null && lstVisibleColumn.FindAll(o => o.ToString() == j.ToString()) != null)
                                {
                                    strBufferLine += table.Rows[i][j].ToString() + delimiter;
                                }
                                else if (lstVisibleColumn == null)
                                    strBufferLine += table.Rows[i][j].ToString() + delimiter;

                                if (j == table.Columns.Count - 1 && table.Columns.Count > 0)
                                    strBufferLine = DelLastComma(strBufferLine);
                            }
                            stringBuilder.AppendLine(strBufferLine);
                        }
                        stringBuilder.AppendLine();
                        stringBuilder.AppendLine("/************************Excel spanned data end**********************/");
                        //if (!keyValuePairs.ContainsKey(path)) //第一次需要添加原先内容
                        //{
                        //    keyValuePairs.Add(path, strings);
                        //    //if (strings.Count > 0)
                        //    //{
                        //    //    for (global::System.Int32 i = 0; i < strings.Count(); i++)
                        //    //    {
                        //    //        var item = strings[i];
                        //    //        sw.WriteLine(item.ToString());
                        //    //    }
                        //    //}
                        //}
                        if (keyValuePairs[path].Count > 0)
                        {
                            var list = keyValuePairs[path];
                            bool fl = false;

                            List<string> DataCollection = new List<string>();
                            for (global::System.Int32 i = 0; i < list.Count(); i++)
                            {
                                var item = list[i];
                                sw.WriteLine(item.ToString());
                                DataCollection.Add(item.ToString());
                                if (item.Equals(fixData) && !fl)
                                {
                                    DataCollection.Add(stringBuilder.ToString());
                                    sw.WriteLine(stringBuilder.ToString()); //插入指定内容
                                    fl = true;
                                }
                            }
                            keyValuePairs[path] = DataCollection;
                        }
                        sw.Close();
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.ToString());
                    }
                    finally
                    {
                        result = true;
                        sw.Close();
                    }
                }
                else
                {
                    Debug.WriteLine(".c/.h文件不存在");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(".c/.h文件不存在");
                Console.ReadLine();
            }

            return result;
        }

        static string fixData = "/************************Fixed Excel spanned data end **********************/";

        /// <summary>
        /// 删除最后结尾的一个逗号
        /// </summary>
        public static string DelLastComma(string str)
        {
            return str.Substring(0, str.LastIndexOf(","));
        }

        public static List<System.Data.DataTable> ReadFromExcelToDatatype(string FilePath, List<int> listSheet = null)
        {
            List<System.Data.DataTable> dataTables = new List<System.Data.DataTable>();
            try
            {
                using (FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
                {
                    XSSFWorkbook workbook = new XSSFWorkbook(fileStream);

                    for (int i = 0; i < workbook.NumberOfSheets; i++)
                    {
                        ISheet sheet = workbook.GetSheetAt(i);
                        DataTable dataTable = new DataTable();
                        dataTable.TableName = sheet.SheetName;

                        IRow headerRow = sheet.GetRow(0);
                        foreach (var cell in headerRow.Cells)
                        {
                            dataTable.Columns.Add(cell.StringCellValue + Guid.NewGuid());
                        }

                        for (int j = (sheet.FirstRowNum + 1); j <= sheet.LastRowNum; j++)
                        {
                            IRow row = sheet.GetRow(j);
                            DataRow dataRow = dataTable.NewRow();
                            for (int k = row.FirstCellNum; k < headerRow.LastCellNum; k++)
                            {
                                if (row.GetCell(k) != null)
                                {
                                    dataRow[k] = row.GetCell(k).ToString();
                                }
                            }
                            dataTable.Rows.Add(dataRow);
                        }

                        dataTables.Add(dataTable);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("生成不成功,请检查文件是否打开!");
                Console.ReadLine();
            }
            return dataTables;
        }

        static Dictionary<string, List<string>> keyValuePairs = new Dictionary<string, List<string>>();

        public static bool DataToStringTXT(string txtpath, DataTable table, string strHeader, List<int> lstVisibleColumn = null, string fileName = "", bool ShowHeader = false)
        {
            bool result = false;
            try
            {
                string delimiter = ",";
                string path = "";
                if (txtpath.Contains(".c"))
                {
                    path = Path.Combine(pathCurrent, "..", Program.config.CodeDirectoryInfo, "source", txtpath);
                }
                else if (txtpath.Contains(".h"))
                {
                    path = Path.Combine(pathCurrent, "..", Program.config.CodeDirectoryInfo, "include", txtpath);
                }
                var strings = new List<string>();
                if (File.Exists(path))
                {
                    bool isappended = true;
                    if (!keyValuePairs.ContainsKey(path))
                    {
                        isappended = false;

                        bool fin = false;
                        strings = LoadFilelistString(path).ToList();
                        var ind1 = 0;
                        var ind2 = 0;
                        for (int i = 0; i < strings.Count; i++)
                        {
                            var itemstring = strings[i];

                            if (!fin && itemstring.Contains("Excel spanned data start"))
                            {
                                ind1 = i;
                                fin = true;
                            }
                            if (itemstring.Contains("Excel spanned data end"))
                            {
                                ind2 = i;
                            }
                        }
                        if (ind1 != 0 && ind2 != 0 && ind2 > ind1)
                        {
                            var count = ind2 - ind1;
                            if (count > 0)
                            {
                                strings.RemoveRange(ind1, count + 1); //删除多余的行
                                ind1 = 0;
                                ind2 = 0;
                            }
                        }
                    }
                    else
                    {
                        isappended = true;
                    }
                    StringBuilder stringBuilder = new StringBuilder();
                    StreamWriter sw = new StreamWriter(path, isappended, Encoding.GetEncoding("GB2312"));
                    try
                    {
                        // Encoding.GetEncoding("GB2312")
                        if (ShowHeader)
                            stringBuilder.AppendLine(strHeader);
                        stringBuilder.AppendLine();
                        stringBuilder.AppendLine("/************************Excel spanned data start**********************/");
                        stringBuilder.AppendLine("/*生成代码*/");
                        for (int i = 0; i < table.Rows.Count; i++)
                        {
                            string strBufferLine = "";
                            for (int j = 0; j < table.Columns.Count; j++)
                            {
                                if (lstVisibleColumn != null && lstVisibleColumn.FindAll(o => o.ToString() == j.ToString()) != null)
                                {
                                    strBufferLine += table.Rows[i][j].ToString() + delimiter;
                                }
                                else if (lstVisibleColumn == null)
                                    strBufferLine += table.Rows[i][j].ToString() + delimiter;

                                if (j == table.Columns.Count - 1 && table.Columns.Count > 0)
                                    strBufferLine = DelLastComma(strBufferLine);
                            }
                            stringBuilder.AppendLine(strBufferLine);
                        }
                        stringBuilder.AppendLine();
                        stringBuilder.AppendLine();
                        stringBuilder.AppendLine();
                        stringBuilder.AppendLine();
                        stringBuilder.AppendLine();
                        stringBuilder.AppendLine("/************************Excel spanned data end**********************/");
                        if (!keyValuePairs.ContainsKey(path)) //第一次需要添加原先内容
                        {
                            keyValuePairs.Add(path, strings);
                            if (strings.Count > 0)
                            {
                                for (global::System.Int32 i = 0; i < strings.Count(); i++)
                                {
                                    var item = strings[i];
                                    sw.WriteLine(item.ToString());
                                }
                            }
                        }
                        sw.WriteLine(stringBuilder.ToString()); //插入指定内容
                        sw.Close();
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.ToString());
                    }
                    finally
                    {
                        result = true;
                        sw.Close();
                    }
                }
                else
                {
                    Debug.WriteLine(".c/.h文件不存在");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(".c/.h文件不存在");
                Console.ReadLine();
            }

            return result;
        }

        public static IEnumerable<string> LoadFilelistString(string FileToRead)
        {
            IEnumerable<string> line = null;
            // Creating enumerable object
            if (File.Exists(FileToRead))
                line = File.ReadLines(FileToRead);
            return line;
        }
    }
}
